﻿using System;
using System.Web.Mvc;
using Agr.Questionnaire.Core.ViewModel.Qnnaire.Queries;
using Agr.Questionnaire.Core.Domain.Qnnaire.Commands;

namespace Agr.Questionnaire.Frontend.Mvc.EditQnnaire
{
    public class EditQnnaireController : AgrQnnaireController
    {
        public ActionResult Index(Guid id)
        {
            return View(getViewModel(id));
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult NewTextQuestion(Guid id, int version, string q)
        {
            CommandIssuer.IssueCommand(new AddTextQuestion
            {
                AffectedAggregateRootId = id,
                AffectedVersion = version,
                QuestionText = q
            });
            return null;
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult RenameQuestionnaire(Guid id, int version, string name)
        {
            CommandIssuer.IssueCommand(new RenameQuestionnaire
            {
                AffectedAggregateRootId = id,
                AffectedVersion = version,
                Name = name
            });
            return null;
        }

        private ViewModel getViewModel(Guid id)
        {
            var model = new ViewModel();
            model.Qnnaire =
                QueryFactory.CreateQuery<QueryQuestionnaireDetail>()
                    .WhereAggregateRootIs(id)
                    .Result();
            return model;
        }

        public ActionResult UpdatedViewModel(Guid id)
        {
            return Json(getViewModel(id), JsonRequestBehavior.AllowGet);
        }
    }
}
